package cn.swenty.backstage.framework.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JsUtils {
	
	public static Object executeScript(String expression){
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine js = manager.getEngineByName("javascript");
		Bindings bindings= js.getBindings(ScriptContext.ENGINE_SCOPE);
		try {
			return js.eval(expression,bindings);
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Object executeScript(File file){
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine js = manager.getEngineByName("javascript");
		Bindings bindings= js.getBindings(ScriptContext.ENGINE_SCOPE);
		try {
			return js.eval(new FileReader(file),bindings);
		} catch (ScriptException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}

